package middlewares

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"shorthand-go/dao/resource"
	"shorthand-go/library/utils/jwt"
)

func NewUserCheckLoginFunc() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 获取 Authorization header 头
		tokenString := ctx.GetHeader("Authorization")
		// 验证token非空
		if tokenString == "" {
			ctx.JSON(http.StatusOK, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "令牌为空",
			})
			ctx.Abort()
			return
		}
		// 验证 token
		customizeClaims, err := jwt.ParseJWT(tokenString)
		if err != nil {
			resource.Logger.Error("解析 token 数据失败", zap.Any("err", err))
			return
		}
		ctx.Set("userInfo", customizeClaims)
	}
}
